<?php

namespace addons\facrm\library\cloudcall;

use think\Exception;

class Call
{

    /**
     * 配置信息
     * @var array
     */
    private $config = [];

    /**
     * 服务提供者
     * @var array
     */
    private $providers = [
        'Tycc100' => 'Tycc100',
        'Moor'    => 'Moor'
    ];
    protected static $instance = null;

    private $engine;    // 当前引擎类

    public function __construct($options = [])
    {
        $this->config = array_merge($this->config, is_array($options) ? $options : []);

        //注册服务提供者
        if (isset($this->config['key'])){
            $this->engine = $this->registerProviders();
        }

    }
    /**
     *
     * @param array $options 参数
     * @return $this
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }else{
            if (isset($options['key'])){
                self::$instance->engine = self::$instance->registerProviders();
            }
        }

        return self::$instance;
    }

    /**
     * 拨打
     * @param $config
     * @param $data
     * @param array $extend 附加参数
     * @return bool
     */
    public function call($data=array(),$extend=array())
    {
        try {
            return $this->engine->call($data,$extend);
        }catch (Exception $e){
            $this->engine->setError($e->getMessage());
            return  false;
        }

    }
    function __call($name,$arguments) {
        return call_user_func_array(array($this->engine, $name), $arguments);
        //return $this->engine->$name($arguments);
    }

    /**
     * 获取通知类型
     * @return array|string[]
     */
    public static function getProviders()
    {
        return (new  self())->providers;
    }

    /**
     * 注册服务提供者
     */
    private function registerProviders()
    {
        $objname = __NAMESPACE__ . "\\engine\\" . $this->providers[$this->config['key']];
        return new $objname($this->config);
    }


    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->engine->getError();
    }


}
